﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseCore
{
    public class StockProductDao : IStockProductDao
    {
        public StockProduct GetStockProduct(string productCode)
        {
            using (var ctx = new ExportDBEntities())
            {
                var stock = (from x in ctx.StockProduct
                             where x.ProductCode == productCode
                             select x).ToList();

                if (stock == null || stock.Count == 0)
                {
                    return null;
                }

                return stock.FirstOrDefault();
            }
        }

        public decimal GetStockQty(string productCode)
        {
            var stock = GetStockProduct(productCode);
            
            if (stock == null)
                return 0;

            return stock.StockQty;
        }

        public bool UpdateStockQty(string productCode, int moveQty)
        {
            var stockQty = GetStockQty(productCode);
            
            //เช็คสต็อกก่อนลง db อีกครั้ง, ถ้าสต็อกไม่พอ อัพเดตไม่ได้
            //if (moveQty > stockQty)
            //    return false;

            // ตัดสต็อกได้ ถ้ามีสต็อกพอ
            using (var ctx = new ExportDBEntities())
            {
                var stocks = (from x in ctx.StockProduct
                             where x.ProductCode == productCode
                             select x).ToList();

                if (stocks == null || stocks.Count == 0)
                {
                    // ไม่มีสินค้านี้ในสต็อกเลย
                    return false;
                }

                var stock = stocks.FirstOrDefault();
                var remainingQty = stock.StockQty;
                stock.StockQty = remainingQty - moveQty;

                return ctx.SaveChanges() > 0;
            }
        }

    }
}
